<?php

namespace addons\groupon\listener\store;

use addons\groupon\exception\Exception;
use addons\groupon\model\Order;
use addons\groupon\model\OrderItem;
use addons\groupon\model\OrderAction;
use addons\groupon\model\User;
use addons\groupon\library\traits\StoreTake;
use addons\groupon\model\store\TakeLog;

/**
 * 自提点佣金
 */
class Take
{
    use StoreTake;

    // 支付成功，立马计算奖金
    public function GrouponOrderPayedAfter(&$params) {
        $order = $params['order'];

        // 重新查询订单
        $order = Order::with('item')->where('id', $order['id'])->find();
        $items = $order ? $order['item'] : [];

        // 添加佣金明细
        foreach ($items as $key => $item) {
            $takeLog = $this->createTakeItem($item);

            if ($takeLog) {
                $this->runTakeMoney($takeLog, 'payed');
            }
        }

    }


    // 确认收货后
    public function GrouponOrderConfirmAfter(&$params) {
        $order = $params['order'];
        $item = $params['item'];

        // 查询 takeLog
        $takeLog = TakeLog::where('order_id', $order['id'])->where('order_item_id', $item['id'])->find();

        if ($takeLog) {
            $this->runTakeMoney($takeLog, 'confirm');
        }
    }


    // 订单全部评价完
    public function GrouponOrderFinish(&$params) {
        $order = $params['order'];

        foreach ($order['item'] as $item) {
            $takeLog = TakeLog::where('order_id', $item['order_id'])->where('order_item_id', $item['id'])->find();
            if ($takeLog) {
                $this->runTakeMoney($takeLog, 'finish');
            }
        }
    }

    // 订单同意退款后
    public function GrouponOrderRefundAfter(&$params)
    {
        $order = $params['order'];
        $item = $params['item'];

        // 查询 takeLog
        $takeLog = TakeLog::where('order_id', $order['id'])->where('order_item_id', $item['id'])->find();

        if ($takeLog) {
            $this->backTakeMoney($takeLog, 'refund');
        }
    }
}
